/*
 * Copyright 2022-2023 the original author(https://github.com/wj596)
 * 
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */
package org.jsets.fastboot.security.listener;

import java.util.List;
import org.jsets.fastboot.security.authc.AuthcRequest;
import org.jsets.fastboot.security.authc.AuthcResult;
import org.jsets.fastboot.util.SpringContextHolder;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
public class IListenerManager {

	private List<IAuthcListener> authcListeners = Lists.newLinkedList();
	private List<IAuthzListener> authzListeners = Lists.newLinkedList();

	public void afterInitialize() {
		SpringContextHolder.tryBeansThen(IAuthcListener.class, map -> {
			map.values().forEach(t -> this.addAuthcListener(t));
		});
		SpringContextHolder.tryBeansThen(IAuthzListener.class, map -> {
			map.values().forEach(t -> this.addAuthzListener(t));
		});
	}

	public void addAuthcListener(IAuthcListener authcListener) {
		this.authcListeners.add(authcListener);
	}
	
	public void addAuthzListener(IAuthzListener authzListener) {
		this.authzListeners.add(authzListener);
	}
	
	public void onLoginSuccess(AuthcRequest request, AuthcResult result) {
		authcListeners.forEach(t->{
			try {
				t.onLoginSuccess(request, result);
			}catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		});
	}

	public void onLoginFailure(AuthcRequest request, String reason) {
		authcListeners.forEach(t->{
			try {
				t.onLoginFailure(request ,reason);
			}catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		});
	}

	public void onLogout(String tokenStubId) {
		authcListeners.forEach(t->{
			try {
				t.onLogout(tokenStubId);
			}catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		});
	}

	public void onRoleAssert(String account, String target, String holds,String needs, boolean allowed){
		authzListeners.forEach(t->{
			try {
				t.onRoleAssert(account, target, holds, needs, allowed);
			}catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		});
	}

	public void onPermissionAssert(String account, String target, String holds, String needs, boolean allowed){
		authzListeners.forEach(t->{
			try {
				t.onPermissionAssert(account, target, holds, needs, allowed);
			}catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		});
	}
}